package com.sumainfor.wx.system.epc.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.sumainfor.common.Constants;
import com.sumainfor.common.exception.TCException;
import com.sumainfor.common.util.*;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.wx.system.config.DataSourceContextHolder;
import com.sumainfor.wx.system.epc.dao.MaintainCommitMapper;
import com.sumainfor.wx.system.feign.BaseFeignTenant;
import com.sumainfor.wx.system.feign.BaseFeignZuul;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author Eddy·Chen
 * @Email 835033913@qq.com
 * @Create 2019-06-12 14:05
 */
@Service
@Log4j2
public class MaintainCommitService {

    @Autowired
    private MaintainCommitMapper mapper;

    @Autowired
    private BaseFeignZuul zuul;

    @Autowired
    private BaseFeignTenant tenant;

    @Autowired
    private ComUtils comUtils;

    /**
     * 查询评价列表
     *
     * @param page
     * @param params
     * @return
     */
    @SuppressWarnings("all")
    public JsonResult queryCommitList(Page page, Map<String, Object> params) {
        params.put("SysUserId", ContextUtils.getUserId());
        List<Map<String, Object>> mapList = mapper.selectCommitList(page, params);
        page.setRecords(mapList);
        for (Map<String, Object> map : mapList) {
            String houId = MapUtils.getString(map, "HouId");
            Map<String, Object> baseInfo = mapper.getHousingBaseInfo(houId);
            map.putAll(baseInfo);
            //是否评价了
            if (MapUtils.getInteger(map, "id") == null) {
                map.put("IsCommit", false);
            } else {
                map.put("IsCommit", true);
            }
            //获取报修人姓名
            map.put("LaunchUserName", "");
            String uid = MapUtils.getString(map, "RepairsId");
            if (MapUtils.getInteger(map, "RepType").equals(1)) {
                //普通用户
                List<Map<String, Object>> uRes = tenant.selectTenantInfoByIdList(Arrays.asList(uid));
                if (CollectionUtils.isNotEmpty(uRes)) {
                    map.put("LaunchUserName", uRes.get(0).get("Realname"));
                }
            } else {
                //管家
                JsonResult<List<Map<String, Object>>> userRes = zuul.getUser(Arrays.asList(uid));
                if (userRes.isSuccess() && CollectionUtils.isNotEmpty(userRes.getResult())) {
                    map.put("LaunchUserName", userRes.getResult().get(0).get("username"));
                }
            }

            map.remove("RepairsId");
            map.remove("RepType");
            map.remove("HouInfoId");
            map.remove("id");
            DateUtils.formatDateByMap(map);
        }
        DataSourceContextHolder.clear();
        return JsonResult.success(page);
    }

    /**
     * 查询订单信息 根据维修工单编号查询
     *
     * @param repId
     * @return
     */
    @SuppressWarnings("all")
    public JsonResult selectOrderInfo(String repId) {
        Map<String, Object> orderInfoData = mapper.getOrderInfoData(repId);
        DateUtils.formatDateByMap(orderInfoData);
        //获取报修人姓名
        orderInfoData.put("LaunchUserName", "");
        orderInfoData.put("LaunchUserPhone", "");
        String uid = MapUtils.getString(orderInfoData, "RepairsId");
        if (MapUtils.getInteger(orderInfoData, "RepType").equals(1)) {
            //普通用户
            List<Map<String, Object>> uRes = tenant.selectTenantInfoByIdList(Arrays.asList(uid));
            if (CollectionUtils.isNotEmpty(uRes)) {
                orderInfoData.put("LaunchUserName", uRes.get(0).get("Realname"));
                orderInfoData.put("LaunchUserPhone", uRes.get(0).get("TenPhone"));
            }
        } else {
            //管家
            JsonResult<List<Map<String, Object>>> userRes = zuul.getUser(Arrays.asList(uid));
            if (userRes.isSuccess() && CollectionUtils.isNotEmpty(userRes.getResult())) {
                orderInfoData.put("LaunchUserName", userRes.getResult().get(0).get("username"));
                orderInfoData.put("LaunchUserPhone", userRes.getResult().get(0).get("mobile"));
            }
        }

        //获取维修师傅信息
        if (StringUtils.isNotBlank(MapUtils.getString(orderInfoData, "SysUserId"))) {
            JsonResult<List<Map<String, Object>>> userRes = zuul.getUser(Arrays.asList(MapUtils.getString(orderInfoData, "SysUserId")));
            if (userRes.isSuccess() && CollectionUtils.isNotEmpty(userRes.getResult())) {
                orderInfoData.put("SysUserName", userRes.getResult().get(0).get("username"));
                orderInfoData.put("SysUserPhone", userRes.getResult().get(0).get("mobile"));
            } else {
                return JsonResult.error("获取维修师傅信息失败:" + userRes.getErrorMessage());
            }
        }

        //查询领用单信息数据
        List<Map<String, Object>> receiveShopList = mapper.selectReceiveShopList(repId);
        orderInfoData.put("ReceiveList", receiveShopList.stream().map(item -> {
            //设置维修状态是否完成
            Integer doneNumber = MapUtils.getInteger(item, "DoneNumber", 0);
            Integer sum = MapUtils.getInteger(item, "RecNumber", 0);
            if (doneNumber.equals(sum)) {
                item.put("DoneSuccess", true);
            } else {
                item.put("DoneSuccess", false);
            }
            item.put("ComType", ShopTypeSelectUtil.selectShopTypeById(MapUtils.getString(item, "ComType")));
            item.remove("DoneNumber");
            return item;
        }).collect(Collectors.toList()));

        //处理图片
        ArrayList<String> imgArray = Lists.newArrayList();
        String completed = MapUtils.getString(orderInfoData, "Completed");
        if (StringUtils.isNotBlank(completed)) {
            for (String s : completed.split(",")) {
                if (StringUtils.isNotBlank(s)) {
                    imgArray.add(s);
                }
            }
        }
        orderInfoData.put("imgArray", imgArray);

        //处理报修图片
        ArrayList<String> troubleFileArray = Lists.newArrayList();
        String troubleFile = MapUtils.getString(orderInfoData, "TroubleFile");
        if (StringUtils.isNotBlank(troubleFile)) {
            for (String s : troubleFile.split(",")) {
                if (StringUtils.isNotBlank(s)) {
                    troubleFileArray.add(s);
                }
            }
        }
        orderInfoData.put("TroubleFile", troubleFileArray);

        //获取房源的房间号
        String hCode = MapUtils.getString(orderInfoData, "HouConId", "").substring(MapUtils.getString(orderInfoData, "HouConId", "").length() - 1);
        orderInfoData.put("hCode", hCode);


        orderInfoData.remove("SysUserId");
        orderInfoData.remove("Completed");
        orderInfoData.remove("RepairsId");
        orderInfoData.remove("RepType");


        //zc修改
        //查询同房源下的待接维修工单
        String zcHouId = MapUtils.getString(orderInfoData, "HouId");
        if (!StringUtils.isBlank(zcHouId)) {
            List<Map<String, Object>> getHouIdRepair = mapper.getHouIdRepair(zcHouId, repId);
            orderInfoData.put("getHouIdRepairList", getHouIdRepair);
        }

        return JsonResult.success(orderInfoData);
    }


    /**
     * 获取房源信息
     *
     * @param repId
     * @return
     */
    public JsonResult getHousingInfo(String repId) {
        String id = mapper.getHousingId(repId);
        Map<String, Object> map = mapper.getHousingBaseInfo(id);
        if (MapUtils.isEmpty(map)) {
            return JsonResult.error("房源不存在");
        }
        //查询服务中心
        Integer miId = MapUtils.getInteger(map, "MiId");
        String name = (String) zuul.getDeptInfoById(miId + "").get("name");
        map.put("CenterName", name);
        //获取维修师傅信息
        JsonResult<List<Map<String, Object>>> userRes = zuul.getUser(Arrays.asList(MapUtils.getString(map, "SysUserId")));
        if (userRes.isSuccess() && CollectionUtils.isNotEmpty(userRes.getResult())) {
            map.put("SysUserName", userRes.getResult().get(0).get("username"));
            map.put("SysUserPhone", userRes.getResult().get(0).get("mobile"));
        } else {
            return JsonResult.error("获取管家信息失败:" + userRes.getErrorMessage());
        }
        return JsonResult.success(map);
    }

    /**
     * 查询账单支付信息
     *
     * @param repId
     * @return
     */
    public JsonResult getOrderPay(String repId) {
        String payOrder = mapper.getPayOrder(repId);
        if (StringUtils.isBlank(payOrder)) {
            return JsonResult.error("没有账单");
        }
        Map<String, Object> payInfo = mapper.getMaintainPayOrderInfo(payOrder);
        DateUtils.formatDateByMap(payInfo);
        return JsonResult.success(payInfo);
    }


    /**
     * 获取维修信息确认提交详情
     *
     * @param repId
     * @return
     */
    @SuppressWarnings("all")
    public Map<String, Object> getDetailConfirm(String repId) {
        //1. 维修物品 2. 报修人姓名 3. 保修描述 4. 保修类型
        Map<String, Object> detail = mapper.getDetailConfirm(repId);
        if (MapUtils.isEmpty(detail)) {
            throw new TCException("维修单不存在");
        }
        //获取报修人姓名
        detail.put("LaunchUserName", "");
        String uid = MapUtils.getString(detail, "RepairsId");
        if (MapUtils.getInteger(detail, "RepType").equals(1)) {
            //普通用户
            List<Map<String, Object>> uRes = tenant.selectTenantInfoByIdList(Arrays.asList(uid));
            if (CollectionUtils.isNotEmpty(uRes)) {
                detail.put("LaunchUserName", uRes.get(0).get("Realname"));
            }
        } else {
            //管家
            JsonResult<List<Map<String, Object>>> userRes = zuul.getUser(Arrays.asList(uid));
            if (userRes.isSuccess() && CollectionUtils.isNotEmpty(userRes.getResult())) {
                detail.put("LaunchUserName", userRes.getResult().get(0).get("username"));
            }
        }
        detail.remove("RepType");
        detail.remove("RepairsId");
        return detail;
    }

    /**
     * 确认维修
     *
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult confirmSubmit(Map<String, Object> params) {

        String repId = MapUtils.getString(params, "RepId");
        //实际报修描述
        String note = MapUtils.getString(params, "note");
        List<String> imgList = (List<String>) MapUtils.getObject(params, "imgList");
        StringBuffer imgStr = new StringBuffer();
        if (CollectionUtils.isNotEmpty(imgList)) {
            for (int i = 0; i < imgList.size(); i++) {
                imgStr.append(imgList.get(i));
                if (i != imgList.size() - 1) {
                    imgStr.append(",");
                }
            }
        }

        //获取主表数据
        Map<String, Object> repairMainData = mapper.getRepairMainData(repId);
        //判断是否维修完成
        if (MapUtils.getInteger(repairMainData, "OrdState").equals(2)) {
            return JsonResult.error("此维修单已维修");
        }

        //修改状态
        int row = mapper.updateRepairMain(ParamsCommon.commonUpdateParms(CustomMap.create("RepId", repId)
                .put("OrdState", 2), getClass()));
        if (row <= 0) {
            return JsonResult.error("操作失败:257");
        }
        row = mapper.updateMyRepair(ParamsCommon.commonUpdateParms(CustomMap.create()
                        .put("RepId", repId)
                        .put("FinishTime", new Date())
                        .put("Notes", note)
                        .put("IfRenew", MapUtils.getBooleanValue(params, "IfRenew") ? 1 : 0)
                        .put("IfCost", MapUtils.getBooleanValue(params, "isMoney") ? 1 : 0)
                        .put("CostPrice", MapUtils.getDouble(params, "price"))
                        .put("Completed", imgStr.toString())
                , getClass()));
        if (row <= 0) {
            throw new TCException("操作失败:266");
        }


        //判断是否是特殊设备
        Map<String, Object> detail = mapper.getDetailConfirm(repId);
        if (Objects.equals(MapUtils.getInteger(detail, "IfReading"), 1)) {
            //特殊设备
            //判断是否需要换新
            if (MapUtils.getBooleanValue(params, "IfRenew")) {
                //获取读表数
                Map<String, Object> meter = (Map<String, Object>) MapUtils.getObject(params, "meter");
                //构建插入数据参数
                CustomMap insertData = CustomMap.create();
                ParamsCommon.commonInsertParms(insertData, getClass());
                insertData.put("OrdMeId", UUIDUtils.generatePrefixUuid("OME"));
                insertData.put("RepId", repId);
                insertData.put("HouId", repairMainData.get("HouId"));
                insertData.put("HouInfoId", repairMainData.get("HouInfoId"));
                insertData.put("HouCon", repairMainData.get("HouCon"));
                //是水表的
                if (MapUtils.getInteger(detail, "ReadingType").equals(1)) {
                    if (!FieldCheckUtil.isMapFieldNotNull(meter, "Water")) {
                        throw new TCException("水表读数请输入完整");
                    }
                    insertData.put("Water", meter.get("Water"));
                }
                //是燃气的
                if (MapUtils.getInteger(detail, "ReadingType").equals(2)) {
                    if (!FieldCheckUtil.isMapFieldNotNull(meter, "Gas")) {
                        throw new TCException("燃气表读数请输入完整");
                    }
                    insertData.put("Gas", meter.get("Gas"));
                }
                //是电表
                if (MapUtils.getInteger(detail, "ReadingType").equals(3)) {
                    if (MapUtils.getInteger(detail, "IfCapacity").equals(0)) {
                        //不是智能电表
                        if (!FieldCheckUtil.isMapFieldNotNull(meter, "EleSum", "ElePeak", "EleFlat")) {
                            throw new TCException("电表读数请输入完整");
                        }
                        insertData.put("EleSum", meter.get("EleSum"));
                        insertData.put("ElePeak", meter.get("ElePeak"));
                        insertData.put("EleFlat", meter.get("EleFlat"));
                    } else {
                        //智能电表
                        if (!FieldCheckUtil.isMapFieldNotNull(meter, "Clever")) {
                            throw new TCException("智能电表读数请输入完整");
                        }
                        insertData.put("Clever", meter.get("Clever"));
                    }
                }
                //进行数据插入操作
                row = mapper.insertOrderMeter(insertData);
                if (row <= 0) {
                    throw new TCException("操作失败:322");
                }
            }
        }

        //是否收费
        boolean isMoney = MapUtils.getBooleanValue(params, "isMoney");
        if (isMoney && Objects.equals(MapUtils.getInteger(repairMainData, "RepType"), 1)) {
            //创建账单
            BigDecimal price = ObjectUtil.convertBigDecimal(MapUtils.getString(params, "price"));

            CustomMap payData = CustomMap.create();
            ParamsCommon.commonInsertParms(payData, getClass());
            String biId = comUtils.getLocalTrmSeqNumByLook("OBID", Constants.DATA_SOURCE_TCEPC, "tcepc_order_bill", "OrdBiId");
            log.info("BiId:{}", biId);
            payData.put("OrdBiId", biId);
            payData.put("RepId", repId);
            payData.put("SysUserId", ContextUtils.getUserId());
            payData.put("HouId", repairMainData.get("HouId"));
            payData.put("HouCon", repairMainData.get("HouCon"));
            payData.put("HouInfoId", repairMainData.get("HouInfoId"));
            payData.put("TenId", repairMainData.get("RepairsId"));
            payData.put("CostPrice", price);
            payData.put("FinishTime", new Date());
            payData.put("Notes", note);
            row = mapper.insertOrderPay(payData);
            if (row <= 0) {
                throw new TCException("操作失败:353");
            }


            //判断是否需要均摊
            boolean payType = MapUtils.getBooleanValue(params, "PayType", false);
            //生成账单主体
            List<Map<String, Object>> orderInMap = Lists.newArrayList();
            if (payType) {
                //均摊
                String houId = MapUtils.getString(repairMainData, "HouId");
                //查询所有的租客Id
                List<String> tenIds = mapper.getPactTenantForHousingId(houId);
                if (org.apache.commons.collections.CollectionUtils.isEmpty(tenIds)) {
                    throw new TCException("无法均摊 系统查询不到此房源有租客入住");
                }
                BigDecimal signPrice = price.divide(new BigDecimal(tenIds.size()));
                for (String tenId : tenIds) {
                    orderInMap.add(CustomMap.create("TenId", tenId)
                            .put("BiMoney", signPrice));
                }
            } else {
                //不均摊
                orderInMap.add(CustomMap.create("TenId", repairMainData.get("RepairsId"))
                        .put("BiMoney", price));
            }

            //通过服务中心编号去找公司编号
            JsonResult<JSONObject> miJson = zuul.getAreaInfoForGSByDeptId(MapUtils.getString(repairMainData, "MiId"));
            if (!miJson.isSuccess()) {
                throw new TCException(miJson.getErrorMessage());
            }
            for (Map<String, Object> map : orderInMap) {
                //创建租客支出账单
                CustomMap tenantBill = CustomMap.create();
                DateTime now = DateTime.now();
                DateTime lastDay = now.plusDays(7);
                tenantBill.put("CorId", miJson.getResult().getString("areaId"));
                tenantBill.put("MainBody", 0);
                tenantBill.put("BiName", "维修账单");
                tenantBill.put("IfTemporary", 0);
                tenantBill.put("BiType", 3);
                tenantBill.put("Source", biId);
                tenantBill.put("BiMoney", map.get("BiMoney"));
                tenantBill.put("BillExplain", String.format("维修账单费用:%s", map.get("BiMoney")));
                tenantBill.put("BiGenerated", now.toDate());
                tenantBill.put("EndTime", lastDay.toDate());
                tenantBill.put("LateDay", lastDay.toDate());
                tenantBill.put("TenId", map.get("TenId"));
                tenantBill.put("HouId", repairMainData.get("HouId"));
                tenantBill.put("HouCon", repairMainData.get("HouCon"));
                tenantBill.put("CreateType", 2);
                tenantBill.put("Create", ContextUtils.getUserId());
                tenantBill.put("ExpStatus", 0);
                tenantBill.put("Status", 1);
                tenantBill.put("Abnormal", 0);
                row = this.addTenantBillOrderPay(tenantBill);
                if (row <= 0) {
                    throw new TCException("操作失败:386");
                }
            }
        }
        return JsonResult.actionSuccess();
    }


    private int addTenantBillOrderPay(CustomMap customMap) {
        ParamsCommon.commonInsertParms(customMap, getClass());
        //获取编号
        String biId = comUtils.getLocalTrmSeqNumByLook("BIO", Constants.DATA_SOURCE_GMIO, "tcgmio_tenant_bill", "BiId");
        customMap.put("BiId", biId);
        return mapper.insertTenantPayOrder(customMap);
    }

}
